<script setup>
	import { ref } from 'vue'
	import { useRouter } from 'vue-router'
	import { useUserStore } from '@/stores'
	import { userUpdatePasswordService } from '@/api/user'
	const router = useRouter()
	const userStore = useUserStore()
	// formRef
	const formRef = ref()
	// 定义响应式表单数据
	const pwdForm = ref({
		old_pwd: '',
		new_pwd: '',
		re_pwd: ''
	})
	// 验证规则
	const checkOldSame = (rule, value, callback) => {
		if (value === pwdForm.value.old_pwd) {
			callback(new Error('新密码与旧密码不能一致'))
		} else {
			callback()
		}
	}
	const checkNewSame = (rule, value, callback) => {
		if (value !== pwdForm.value.new_pwd) {
			callback(new Error('两次输入的新密码不一致'))
		} else {
			callback()
		}
	}
	// 定义表单验证规则
	const rules = {
		old_pwd: [
			{ required: true, message: '请输入原密码', trigger: 'blur' },
			{
				pattern: /^\S{6,15}$/,
				message: '密码长度为6-15位的非空字符',
				trigger: 'blur'
			}
		],
		new_pwd: [
			{ required: true, message: '请输入新密码', trigger: 'blur' },
			{
				pattern: /^\S{6,15}$/,
				message: '密码长度为6-15位的非空字符',
				trigger: 'blur'
			},
			{ validator: checkOldSame, trigger: 'blur' }
		],
		re_pwd: [
			{ required: true, message: '请确认新密码', trigger: 'blur' },
			{
				pattern: /^\S{6,15}$/,
				message: '密码长度为6-15位的非空字符',
				trigger: 'blur'
			},
			{ validator: checkNewSame, trigger: 'blur' }
		]
	}
	// 提交方法
	const onSubmit = async () => {
		// 验证
		const valid = await formRef.value.validate()
		// 如果通过验证验证通过，则提交请求
		if (valid) {
			// 提交请求
			await userUpdatePasswordService(pwdForm.value)
			// 提示成功，然后清空token,用户信息，回到login页
			ElMessage.success('修改成功')
			userStore.setToken('')
			userStore.setUser({})
			router.push('/login')
		}
	}
	// 重置方法
	const onReset = () => {
		// 重置表单
		formRef.value.resetFields()
	}
</script>
<template>
	<page-container title="重置密码">
		<el-form
			:model="pwdForm"
			:rules="rules"
			ref="formRef"
			label-width="100px"
			size="large"
		>
			<el-form-item label="原密码" prop="old_pwd">
				<el-input
					placeholder="请输入原密码"
					v-model="pwdForm.old_pwd"
					type="password"
				></el-input>
			</el-form-item>
			<el-form-item label="新密码" prop="new_pwd">
				<el-input
					placeholder="请输入新密码"
					v-model="pwdForm.new_pwd"
					type="password"
				></el-input>
			</el-form-item>
			<el-form-item label="确认新密码" prop="re_pwd">
				<el-input
					placeholder="请再次输入新密码"
					v-model="pwdForm.re_pwd"
					type="password"
				></el-input>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" @click="onSubmit()">修改密码</el-button>
				<el-button @click="onReset()">重置</el-button>
			</el-form-item>
		</el-form>
	</page-container>
</template>
<style></style>
